package org.example.collect;

import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/*链表：擅长增删改，不擅长查询*/
public class CustomLinkedList {

    private LinkedList<String> list;

    public CustomLinkedList(String ... elements){
        this.list=new LinkedList<String>();
        for (int i = 0; i <elements.length ; i++) {
            list.add(elements[i]);
        }
    }

    public void print(boolean isToString){
        if(!isToString){
            System.out.println("元素包括：");
            for(String ele:list){
                System.out.print(ele);
                System.out.print("   ");

            }
            System.out.println("\r\n-----------");
        }
        else{
            System.out.println("元素包括：");
            System.out.print(list.toString());
            System.out.println("\n----------");
        }
    }

    public String max(){
        String max = list.get(0);
        for (int i = 0; i <list.size() ; i++) {
            String ele = list.get(i);
            if(null!=ele && ele.compareTo(max)>0){
                max=ele;
            }
        }
        return max;
    }

    public void removeEle(String ele){
        list.remove(ele);
    }

    public void removeByIdx(int idx){
        if(idx>=list.size()){
            return;
        }
        list.remove(idx);
    }

    public void add(int idx,String ele){
        int maxIdx=list.size()-1;
        if(idx>maxIdx){
            list.add(ele);
        }
        else list.add(idx,ele);
    }

    public void add(String ele){
        list.add(ele);
    }

    public void addFirst(String ele){
        list.addFirst(ele);
    }

    public void  addLast(String ele){
        list.addLast(ele);
    }

    public void asc(){
        Collections.sort(list);
    }

    public void desc(){
        Collections.sort(list,Collections.<String>reverseOrder());
    }

    public void exclusive(String max){
        List<String> res=new LinkedList<>();
        // list遍历iterator，才可以直接删除list中元素。list的for、while循环中不允许添加删除list的元素
        Iterator<String> iterator=list.iterator();
        while(iterator.hasNext()){
            String ele=iterator.next();
            if(ele.compareTo(max)>0){
                iterator.remove();
            }
        }

    }

}
